package com.jiankangjin.pay.util;


import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * String工具类
 * 
 * @author yangliehui
 * 
 */
public class StringUtil {
	/**
	 * 判断是否为空
	 * 
	 * @param arg
	 *            要判断的参数
	 * @return boolean 是否为空
	 */
	public static boolean isEmpty(String amount) {
		return ((null == amount) || ("".equals(amount.trim())) || (0==amount.trim().length()) || ("{}".equals(amount)) || ("[]".equals(amount)));
	}

	/**
	 * 判断是否不为空
	 * 
	 * @param arg
	 *            要判断的参数
	 * @return boolean 是否不为空
	 */
	public static boolean isNotEmpty( String str ) {
		return ( ( str != null ) && ( str.trim().length() > 0 ) ) || (!(isEmpty(str)));
	}

	/**
	 * 判断str是不是日期格式
	 * 
	 * @param strDate 
	 * @return true 是日期格式
	 */
	public static boolean validateData(String strDate) {
		String regex = "[2]\\d{3}[0|1][1-9][0-3]\\d";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(strDate);
		return matcher.matches();
	}

	/**
	 * 手机规则判断
	 * 
	 * @param telePhone
	 *            手机号数组
	 * @return boolean 手机数组中是否都正确
	 */
	public static boolean validatePhone(String[] telePhone) {
		String regex = "^(1(([35][0-9])|(47)|[8][0126789]))\\d{8}$";
		Pattern pattern = Pattern.compile(regex);
		for (int i = 0; i < telePhone.length; i++) {
			Matcher matcher = pattern.matcher(telePhone[i]);
			if (!matcher.matches()) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Replaces all instances of oldString with newString in line.
	 * 
	 * @param line
	 *            the String to search to perform replacements on
	 * @param oldString
	 *            the String that should be replaced by newString
	 * @param newString
	 *            the String that will replace all instances of oldString
	 * @return a String will all instances of oldString replaced by newString
	 */
	public static final String replace(String line, String oldString,
			String newString) {
		if (line == null) {
			return null;
		}
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		return line;
	}

	/**
	 * 把对象转换成字符串
	 * 
	 * @param obj
	 * @return String 转换成字符串,若对象为null,则返回空字符串.
	 */
	public static String toString(Object obj) {
		if (obj == null)
			return "";

		return obj.toString();
	}

	/**
	 * 把对象转换为int数值.
	 * 
	 * @param obj
	 *            包含数字的对象.
	 * @return int 转换后的数值,对不能转换的对象返回0。
	 */
	public static int toInt(Object obj) {
		int a = 0;
		try {
			if (obj != null)
				a = Integer.parseInt(obj.toString());
		} catch (Exception e) {

		}
		return a;
	}

	/**
	 * 取出一个指定长度大小的随机正整数.
	 * 
	 * @param length
	 *            int 设定所取出随机数的长度。length小于11
	 * @return int 返回生成的随机数。
	 */
	public static int buildRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));
	}

	/**
	 * 时间转换成字符串
	 * 
	 * @param date
	 *            时间
	 * @param formatType
	 *            格式化类型
	 * @return String
	 */
	public static String date2String(Date date, String formatType) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatType);
		return sdf.format(date);
	}

	public static String StringDateToFormatType(String strDate,
			String formatType) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatType);
		String dateStr = "";
		try {
			dateStr = sdf.format(sdf.parse(strDate));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dateStr;
	}

	public static String StringDateToFormatType2(String strDate,
			String fromType, String formatType) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatType);
		SimpleDateFormat sdf1 = new SimpleDateFormat(fromType);
		String dateStr = "";

		try {
			Date da2 = sdf1.parse(strDate);
			dateStr = sdf.format(da2);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dateStr;
	}

	public static void main(String[] args) {
//		System.out.println(StringUtil.StringDateToFormatType2("20110221",
//				"yyyyMMdd", "yyyy/MM/dd"));
//		System.out.println(StringUtil.getStringToDate("2012-1"));
//		System.out.println("===========>"+StringUtil.yuan2Fen(""));
//		System.out.println(StringUtil.isNumer("1")); 
//		System.out.println("----"+StringUtil.formatFenToYuan(111));
//		System.out.println("----="+StringUtil.yuan2Fen("111"));
		String ss = "  ss   ";
		System.out.println(isTradeId("!@s1111111111111111111111111111111111111111"));
//		String s = "22";
//		String[] ss = s.split(",",0);
//		for (String string : ss) {
//			System.out.println(string);
//		}
//		System.out.println(ss.length);
		
		
	}

	/**
	 * 获取当前时间
	 * 
	 * @param format
	 *            格式
	 * @return
	 */
	public static String getCurrTime(String format) {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat(format);
		String s = outFormat.format(now);
		return s;
	}

	public static String formatYuanToFen(String amt) {
		return formatYuanToFen(Double.parseDouble(amt));
	}

	public static String formatYuanToFen(double amt) {
		return String.valueOf(Math.round(amt * 100.0D));
	}

	public static String formatFenToYuan(String amt) {
		return ((isEmpty(amt)) ? "" : decimal(Double.parseDouble(amt) / 100.0D));
	}

	public static String formatFenToYuan(long amt) {
		return decimal(amt / 100.0D);
	}

	public static String formatFenToYuan(int amt) {
		return decimal(amt / 100.0D);
	}

	public static String formatFenToYuan(double amt) {
		return decimal(amt / 100.0D);
	}

	public static String decimal(double amt) {
		long result1 = 0L;
		if (amt > 0.0D)
			result1 = (long) (amt * 100.0D + 0.5D);
		else {
			result1 = (long) (amt * 100.0D - 0.5D);
		}

		if (result1 == 0L)
			return "0.00";
		String result;
		if (result1 > 0L) {
			result = "" + result1;

			result = fill(result, 3);
			result = result.substring(0, result.length() - 2) + "."
					+ result.substring(result.length() - 2);
		} else {
			result = "" + Math.abs(result1);
			result = fill(result, 3);
			result = "-" + result.substring(0, result.length() - 2) + "."
					+ result.substring(result.length() - 2);
		}
		return result;
	}

	public static String fillLeft(String str, int length, char c) {
		StringBuffer buffer = new StringBuffer("");

		if (str == null) {
			str = "";
		}

		if (length <= str.length()) {
			return str;
		}
		int strLen = length - str.length();
		for (int i = 0; i < strLen; i++) {
			buffer.append(c);
		}

		buffer.append(str);
		return buffer.toString();
	}

	public static String fillRight(String str, int length, char c) {
		StringBuffer buffer = new StringBuffer("");

		if (str == null) {
			str = "";
		}

		if (length <= str.length()) {
			return str;
		}
		buffer.append(str);
		int strLen = length - str.length();
		for (int i = 0; i < strLen; i++) {
			buffer.append(c);
		}

		return buffer.toString();
	}

	public static String fill(String str, int length) {
		return fillLeft(str, length, '0');
	}

	public static String fill(int number, int length) {
		StringBuffer buffer = new StringBuffer("");
		String str;
		if (number >= 0) {
			str = "" + number;
		} else {
			buffer.append("-");
			str = "" + Math.abs(number);
			length--;
		}
		buffer.append(fill(str, length));
		return buffer.toString();
	}

	public static String fill(String str) {
		if ((str == null) || (str.trim().equalsIgnoreCase("null"))) {
			return "";
		}
		return str;
	}
	
	/**
	 * List判重
	 * @param list
	 * @return
	 */
	public static List<String> removeDuplicateWithOrder(List<String> list) { 
        HashSet<String> hashSet = new HashSet<String>(); 
        List<String> newlist = new ArrayList<String>(); 
        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { 
            String element = (String) iterator.next(); 
            if (hashSet.add(element)) { 
                newlist.add(element); 
            } 
        } 
        list.clear(); 
        list.addAll(newlist); 
        return list; 
    }
	/**
     * 把元为单位的数字转化为分为单位
     * @param num 待格式化的数值
     * @return 转换后的值
     */
    public static long yuan2Fen(String num) {
        long fen=0L;
        String fenStr ="";
        try {
	        int pos = num.indexOf(".");
	        
	        if( pos == -1 ) {
	            fenStr = num + "00";
	        } else {
	            // 取小数点前的值
	            fenStr = num.substring(0,pos);
	            if( num.length() - pos >= 3 ) {     // 小数点后面大于等于2位
	                fenStr += num.substring( pos+1,pos+3 );
	            } else if( num.length() == pos ){   // 小数点后面没有值
	                fenStr += "00";
	            }else {                              // 小数点后面1位
	                fenStr += num.substring( pos+1 ) + "0";
	            }
	        }
       
            fen = Long.parseLong(fenStr);
        }catch(Exception e) {
            return 0L;
        }
        return fen;
    }
    
     /**
	 * 将分转换为元
	 * @param amountStr
	 * @return
	 */
	public static String parseAmountLong2Str(Long amountLong){
		if(amountLong==null){
			return "0.00";
		}
		DecimalFormat df = new DecimalFormat("0.00");
		double d = amountLong/100d;
		String s = df.format(d);
		return s;
	}
	
	/**
	 * 将String转换为double
	 * @param str
	 * @return
	 */
	public static double parseStr2Dou(String str){
		double d = Double.parseDouble(str);
/*		DecimalFormat df = new DecimalFormat("######0.00");   */
		return d;
	}
	/**
	 * 将String类型的年月转换成日期
	 * @param ts
	 * @return
	 */
	public static Date getStringToDate(String ts) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		try {
			return formatter.parse(ts);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Date
	 */
	public static boolean dateIsEmpty(Date date){
		return (null==date);
	}
	/**
	 * 验证字符串是否为纯数字
	 * 
	 * @param aStr
	 * @return
	 * @author Hippo
	 */
	public static boolean isNumeric(String aStr) {
		if (null == aStr || aStr.equals("")) {
			return false;
		}
		int tSz = aStr.length();
		for (int i = 0; i < tSz; ++i) {
			if (!(Character.isDigit(aStr.charAt(i)))) {
				return false;
			}
		}
		return true;
	}
	/**
	 * 判断字符串是否为整数或小数
	 * @param str
	 * @return
	 */
	public static boolean isNumer(String str){
		String reg = "\\d+(\\.\\d+)?";
		return str.matches(reg);
	}
	/**
	 * 将String类型的年月转换成日期
	 * @param ts
	 * @return
	 */
	public static Date getStringToDateFormat(String ts) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return formatter.parse(ts);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 验证是否是金额
	 * @param amount
	 * @return true 是金额
	 */
	public static boolean isAmount(String amount){
		if(isEmpty(amount)){
			return false;
		}
    	String amountMaches="[0-9]*[.]{1}[0-9]{2}";
		return Pattern.matches(amountMaches, amount);
	}
	/**
	 * 交易号格式验证
	 * @param tradeId
	 * @return true 是交易号
	 */
	public static boolean isTradeId(String tradeId){
		if(isEmpty(tradeId)){
			return false;
		}
    	String  tranIdMaches="[0-9,a-z,A-Z]{1}[0-9,a-z,A-Z,_,-]*"; 
    	return Pattern.matches(tranIdMaches, tradeId);
	}
	/**
	 * 日期时间格式判断
	 * @param strDate
	 * @return true 是日期时间格式
	 */
	public static boolean IsDateTimeString(String strDate){   
		boolean flag = true;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		sdf.setLenient(false);
		try {
			sdf.parse(strDate);
		} catch (Exception e) {
			flag = false;
			return flag;
		}
		String strRegex = "^[0-9]{14}$";
		Pattern pattern = Pattern.compile(strRegex);
        Matcher m=pattern.matcher(strDate);
        flag = m.matches();
	    return flag;
	}
	
	/**
	 * 判断是否是url
	 * @param str_url
	 * @return true url格式正确
	 */
	public static boolean IsURL(String str_url){
		if(isEmpty(str_url)){
			return false;
		}
        String strRegex = "^((https|http|ftp|rtsp|mms)://)"   
        + "(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@   
        + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184   
        + "|" // 允许IP和DOMAIN（域名）  
        + "(([0-9a-zA-Z_!~*'()-]+\\.)*" // 域名- www.   
        + "([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\." // 二级域名   
        + "[a-zA-Z]{2,6})|([0-9a-zA-Z]{1,}))" // first level domain- .com or .museum 
        + "(:[0-9]{1,4})?" // 端口- :80   
        + "((/?)|" // a slash isn't required if there is no file name   
        + "(/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 
        Pattern pattern = Pattern.compile(strRegex);
        Matcher m=pattern.matcher(str_url.trim());  
        return m.matches();
    }  
}
